<?php
/**
 * 示例控制器
 */
namespace app\ctrl;


use EasyWeChat\Factory;
use ppphp\cache;
use ppphp\conf;
use ppphp\view;

class indexCtrl extends \ppphp
{
    use view;

    public function index()
    {
        redirect('app.html');
    }

    public function create()
    {
        $img_url = post('img_url');
        $key = md5($img_url);
        $cache = new cache();
        $cache->set($key,$img_url);

        json([
            'key'=>$key,
            'url'=>'http://'.$_SERVER['HTTP_HOST'].'/share?id='.$key
        ]);
    }

    public function share()
    {
        $id = get('id');
        $step = get('step','int',1);
        $cache = new cache();
        $result = $cache->get($id);
        if($result) {
            $this->assign('ret_url', $result);
            $this->assign('id', $id);
            if($step == 1) {
                $this->display('share.html');
            } else {
                $this->display('share2.html');
            }
        } else {
            exit();
        }
    }

    /**
     * @return array
     */
    public function jssdk()
    {
        $config = conf::all('wechat');
        $app    = Factory::officialAccount($config);
        $APIs   = [
            'onMenuShareTimeline',
            'onMenuShareAppMessage'
        ];

        $app->jssdk->setUrl($_SERVER['HTTP_REFERER']);
        $json = $app->jssdk->getConfigArray($APIs, false, false, $json = false);

        json($json);
        exit();
        return true;
    }

    public function getCar()
    {
        $name = get('name');
        $text = htmlspecialchars_decode(get('text'));

        $text = str_replace('p', 'span', $text);
        $text = str_replace('XXX', $name, $text);

        $ret = conf::all('cars');


        if (false) {
            $index = base_convert($name, 16, 10) % (count($ret) - 1);
        }

        else {
            $index = mt_rand(0, count($ret) - 1);
        }
        $ret[$index]['text'] = $text;
        json($ret[$index]);
        exit();
        return true;
    }

}